'use strict';

const axios = require('axios');
const urlJoin = require('url-join');
const semver = require('semver');

function getNpmInfo(npmName,registry) {
    if(!npmName){
        return null
    };
    const registryUrl = registry || getDefaultRegistry();
    const getNpmInfoUrl = urlJoin(registryUrl,npmName);
    // 调用npm API，获取所有版本号
    return axios.get(getNpmInfoUrl).then(res=>{
        if(res.status === 200){
            return res.data
        };
        return null;
    }).catch(err=>{
        return Promise.reject(err)
    })
};

function getDefaultRegistry(isOriginal=false){
    return isOriginal?'https://registry.npmjs.org':'https://registry.npm.taobao.org'
};

// 获取所有包的version
async function getNpmVersions(npmName,registry){
    const data = await getNpmInfo(npmName,registry);
    if(data){
        return Object.keys(data.versions)
    }else{
        return []
    }
}

// 筛选出大于当前版本的version
function getSemverVersions(baseVersion,versions){
    return versions
        .filter(
            // 提取所有版本号，比对有哪些大于当前版本的版本号
            v => semver.satisfies(v,`^${baseVersion}`)
        )
        // 对得到的大于当前的版本数组进行排序，从大到小
        .sort((a,b)=>semver.gt(b,a))
}

async function getNpmServerVersion(npmName,baseVersion,registry){
    const versions = await getNpmVersions(npmName,registry);
    const newVersions = getSemverVersions(baseVersion,versions);
    // 将大于当前的版本号中最新的一个版本号提取出来并提示用户去更新
    if(newVersions&&newVersions.length>0){
        return newVersions[0]
    }else{
        return null
    }
}

async function getNpmLatestVersion(npmName,registry){
    let versions = await getNpmVersions(npmName,registry);
    if(versions){
        return versions.sort((a,b)=>semver.gt(b,a))[0]
    }
    return null
}

module.exports = {
    getNpmInfo,
    getNpmVersions,
    getNpmServerVersion,
    getDefaultRegistry,
    getNpmLatestVersion
};

